package com.example.Android_test.activity.training;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.Android_test.R;
import com.example.Android_test.activity.Main;
import com.example.Android_test.helpers.SOWEngine;
import com.example.Android_test.helpers.SettingsHelper;
import com.example.Android_test.specs.WordSpec;
import com.example.Android_test.util.StringUtils;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: anpi0413
 * Date: 20.05.13
 * Time: 12:02
 * To change this template use File | Settings | File Templates.
 */
public class Training_TypeWriting extends Abstract_Training {
    private WordSpec trainingWord;
    private int currentPos;

    TextView rusWordView;

    @Override
    protected void onFirstRun() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    protected String getKeyTrainingTimeSpent() {
        return SettingsHelper.KEY_TRAINING_TIME_SPENT_TW;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.training_typewriting);
        setTitle("Training_TypeWriting");


        rusWordView = (TextView) findViewById(R.id.twt_rusWordTextView);

        Button nextButton = (Button) findViewById(R.id.twt_nextButton);
        nextButton.setOnClickListener(new ButtonNextListener());

        next();
    }

    @Override
    protected void next() {
        try {
            trainingWord = SOWEngine.INSTANCE.getWordToTraining();
        } catch (Exception e) {
            Log.e(Main.LOG_TAG, "Unable to load wort to training " + e.getMessage());
            return;
        }

        currentPos = 0;

        rusWordView.setText(trainingWord.getTranslationVariantSpecs().get(0).getTranslate());

        createButtons((TableLayout) findViewById(R.id.twt_completeLayout), trainingWord.getWord(), false);
        createButtons((TableLayout) findViewById(R.id.twt_variantLayout), StringUtils.shuffleChars(trainingWord.getWord()), true);
    }

    private void createButtons(TableLayout tableLayout, String word, boolean printChars) {
        tableLayout.removeAllViews();

        TableRow.LayoutParams param = new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.MATCH_PARENT, 1.0f);

        final int CHARS_IN_LINE = 8;

        int pos = CHARS_IN_LINE;
        TableRow tr = null;
        for (int ch_num = 0; ch_num < word.length(); ch_num++) {
            if (pos == 0) {
                tableLayout.addView(tr, new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                pos = CHARS_IN_LINE;
            }

            if (pos == CHARS_IN_LINE) {
                tr = new TableRow(this);
                //tr.setWeightSum(CHARS_IN_LINE - 1);
                //tr.set
            }

            Button button = new Button(this);
            button.setLayoutParams(param);
            button.setOnClickListener(new ButtonVariantListener());
            if (!printChars) button.setTag(ch_num); // only for completed buttons
            if (printChars) button.setText(word.substring(ch_num, ch_num + 1)); // only for variant buttons

            /*Resources res = getResources();
            Drawable buttonCustomDrawable = res.getDrawable(R.drawable.button_custom);
            button.setBackground(buttonCustomDrawable);*/

            tr.addView(button);

            pos--;
        }

        if (pos >= 0) {
            tableLayout.addView(tr, new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }

    private class ButtonVariantListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            //To change body of implemented methods use File | Settings | File Templates.
            // Toast.makeText(instance(), "Нажата кнопка ОК", Toast.LENGTH_LONG).show();
            Button clickedButton = (Button) v;

            if (clickedButton.getText().equals(trainingWord.getWord().substring(currentPos, currentPos + 1))) {
                TableLayout tl = (TableLayout) findViewById(R.id.twt_completeLayout); //
                ArrayList<View> touchables = tl.getTouchables();
                for (View touchable : touchables) {
                    if (touchable instanceof Button) {
                        int tag = (Integer) touchable.getTag();
                        if (tag == currentPos)
                            ((Button) touchable).setText(trainingWord.getWord().substring(currentPos, currentPos + 1));
                    }
                }

                animateButtonRight(clickedButton);

                currentPos++;
            } else {
                animateButtonWrong(clickedButton);
            }

            if (currentPos > trainingWord.getWord().length()) {
                trainingWord.setRating(trainingWord.getRating() + 1);
                trainingWord.setShowed(trainingWord.getShowed() + 1);

                SOWEngine.INSTANCE.saveCurrentSetOfWords();
            }
        }
    }

    private void animateButtonRight (Button button) {
        button.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out));
        button.setVisibility(View.INVISIBLE);
    }

    private void animateButtonWrong (Button button) {
        final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
        animation.setDuration(100); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(2); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

        button.startAnimation(animation);
    }

    private class ButtonNextListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (currentPos < trainingWord.getWord().length()) {
                /*TableLayout tl = (TableLayout) findViewById(R.id.twt_variantLayout); //
                ArrayList<View> touchables = tl.getTouchables();

                int pos = 0;
                for (View globalLoop : touchables) {
                    for (View touchable : touchables) {
                        if (touchable instanceof Button) {
                            ((Button)touchable).performClick();
                        }
                    }
                }*/
                TableLayout tl = (TableLayout)findViewById(R.id.twt_completeLayout); //
                ArrayList<View> touchables = tl.getTouchables();
                for(View touchable : touchables)
                {
                    if (touchable instanceof Button)  {
                        int tag = (Integer) touchable.getTag();
                        ((Button)touchable).setText(trainingWord.getWord().substring(tag, tag + 1));
                    }
                }

                tl = (TableLayout)findViewById(R.id.twt_variantLayout); //
                touchables = tl.getTouchables();
                for(View touchable : touchables)
                {
                    if (touchable instanceof Button)  {
                        animateButtonRight((Button) touchable);
                    }
                }

                currentPos = trainingWord.getWord().length();
            } else {
                next();
            }
        }
    }
}